package cn.com.ddapp.ddm.ui;


import android.app.ActionBar;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.MainActivity;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.adapter.GoodBrowAdapter;
import cn.com.ddapp.ddm.adapter.GoodLikeAdapter;
import cn.com.ddapp.ddm.adapter.GoodValueAdapter;
import cn.com.ddapp.ddm.adapter.GoodValueLimitAdapter;
import cn.com.ddapp.ddm.adapter.LandGoodImageAdapter;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Banner;
import cn.com.ddapp.ddm.bean.DetailsBean;
import cn.com.ddapp.ddm.bean.Entity;
import cn.com.ddapp.ddm.bean.GoodsCollectBean;
import cn.com.ddapp.ddm.bean.HomeBean;
import cn.com.ddapp.ddm.bean.mine.MyCall;
import cn.com.ddapp.ddm.bean.shopcar.ShopcarEntity;
import cn.com.ddapp.ddm.fragment.base.commidcontext.EffectContextFragment;
import cn.com.ddapp.ddm.fragment.base.commidcontext.FormatFileFragment;
import cn.com.ddapp.ddm.fragment.base.commidcontext.UsersContextFragment;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.BannerUtil;
import cn.com.ddapp.ddm.util.JsonHttpNet;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import cn.com.ddapp.ddm.util.ToastUtil;

/**
 * Created by Administrator on 2016/8/22 0022.//商品详情
 */
public class CommidContentActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.right_btn)
    ImageView rightBtn;
    @BindView(R.id.commidinfo)
    TextView commidinfo;
    @BindView(R.id.commidprice)
    TextView commidprice;
    @BindView(R.id.zhepirce)
    TextView zhepirce;
    @BindView(R.id.dizhitext)
    TextView dizhitext;
    @BindView(R.id.fragLayout)
    FrameLayout fragLayout;
    @BindView(R.id.startImage)
    ImageView startImage;
    @BindView(R.id.error_layout)
    EmptyLayout error_layout;
    @BindView(R.id.tuwenButton)
    RadioButton tuwenButton;
    @BindView(R.id.xiaoguoButton)
    RadioButton xiaoguoButton;
    @BindView(R.id.yonghuButton)
    RadioButton yonghuButton;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.bannerview)
    RelativeLayout bannerview;
    @BindView(R.id.collectLayout)
    LinearLayout collectLayout;
    @BindView(R.id.catLayout)
    LinearLayout catLayout;
    @BindView(R.id.cattext)
    TextView cattext;
    @BindView(R.id.buytext)
    TextView buytext;
    @BindView(R.id.xiaoliangg)
    TextView xiaoliangg;
    @BindView(R.id.kucunc)
    TextView kucunc;
    @BindView(R.id.shouc_text)
    TextView shoucText;
    @BindView(R.id.gdetails_toaddress)
    ImageView gdetails_toaddress;
    @BindView(R.id.shiping)
    ImageView shiping;
    @BindView(R.id.land_goodname)
    TextView land_goodname;
    @BindView(R.id.land_goodpreprice)
    TextView land_goodpreprice;
    @BindView(R.id.land_goodprice)
    TextView land_goodprice;
    @BindView(R.id.land_goodsales)
    TextView land_goodsales;
    @BindView(R.id.land_goodkucun)
    TextView land_goodkucun;
    @BindView(R.id.land_reduce)
    TextView land_reduce;
    @BindView(R.id.land_score)
    TextView land_score;
    @BindView(R.id.land_add)
    TextView land_add;
    @BindView(R.id.land_goodallprice)
    TextView land_goodallprice;
    @BindView(R.id.land_cat)
    TextView land_cat;
    @BindView(R.id.land_buytext)
    TextView land_buytext;
    @BindView(R.id.land_goodnum)
    TextView land_goodnum;
    @BindView(R.id.land_cartnum)
    TextView land_cartnum;//购物车数量
    @BindView(R.id.land_tocart)
    ImageView land_tocart;
    @BindView(R.id.land_collectionimg)
    ImageView land_collectionimg;
    @BindView(R.id.land_collectiontv)
    TextView land_collectiontv;
    @BindView(R.id.land_kefuimg)
    ImageView land_kefuimg;
    @BindView(R.id.land_goodimg)
    ImageView land_goodimg;
    @BindView(R.id.land_goodsmall)
    GridView land_goodsmall;
    @BindView(R.id.land_goodlbtview)
    RecyclerView land_goodlbtview;
    @BindView(R.id.land_goodleftview)
    RecyclerView land_goodleftview;
    @BindView(R.id.toplay)
    TextView toplay;
    @BindView(R.id.land_goodsort)
    TextView land_goodsort;
    @BindView(R.id.land_goodfashu)
    TextView land_goodfashu;
    @BindView(R.id.details_ll)
    LinearLayout details_ll;
    @BindView(R.id.yongList)
    ListView yongList;
    private FormatFileFragment formatfileFragment;
    private EffectContextFragment effectContextFragment;
    private UsersContextFragment usersContextFragment;
    private FragmentManager fragmentManager;
    private Fragment currentFragment;
    private String goodsId1;
    private View popupContentView;
    private PopupWindow popupWindow;
    private TextView minus;
    private TextView add;
    private TextView addCar;
    private TextView goBuy;
    private DetailsBean.DetailBean.GoodsBean goods;
    private DetailsBean.DetailBean deBean;
    private int num;
    private int goodsId,shopcarNum;
    private String catpath;
    private Dialog dialog;
    private ImageView backCommid;
    private Intent intent;
    private TextView score;
    private TextView diogpirce;
    private String shouUrl,landshouUrl;
    private GoodsCollectBean goodsCollectBean;
    private int flag;
    private boolean booleanData;
    String[] temp;
    String[] tems;
    private boolean isFollow;
    private LandGoodImageAdapter landApater;
    private int land_carNum;
    private String userId,myPhone;
    private List<DetailsBean.BrowseGood> broList;
    private List<DetailsBean.LikeBrandGood> likeList;
    private HomeBean homeBean;
    private GoodValueAdapter goodApater;
    private GoodValueLimitAdapter goodlimitApater;
    private List<DetailsBean.DetailBean.GoodKey> valuelist;
    final ArrayList<String> arrayList = new ArrayList<String>();
    private String goodsNum;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        booleanData = SPUtils.getBooleanData(CommidContentActivity.this, SPUtils.ISGOODS);

    }

    @Override
    public void initView() {
        rightBtn.setVisibility(View.GONE);//分享图标可见
        setTitle("商品详情");
        setTitleLeftImg(R.mipmap.back_icon, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });//头部的点击事件返回

        goodsId1 = getIntent().getExtras().getString("id");//获取id
        userId = SPUtils.getStringData(CommidContentActivity.this, SPUtils.USERID);
        goodsNum = getIntent().getStringExtra("goodsNum");

        if(!TextUtils.isEmpty(userId)){
//            details_ll.setVisibility(View.VISIBLE);
            getShopNum();
        }else if(TextUtils.isEmpty(userId)){
//            details_ll.setVisibility(View.GONE);
        }
        dizhitext.setText(AppConfig.City_NAME);
        initFirstData();//商品详情页面的数据展示
        getCoustomPhone();
        AppConfig.TEMP=1;
    }

    private void getCoustomPhone() {
        final OkUtilCallback callback1 = new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                Gson gson = new Gson();
                MyCall call = gson.fromJson(response, MyCall.class);
                if (call.getContent() != null) {
                    myPhone = call.getContent();
                }
            }
        };
        //客服热线
        OKUtilAPI.post(OKUtilAPI.art, "type=4", callback1);
    }

    private void getShopNum() {
        final OkUtilCallback okUtilCallback =  new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                ShopcarEntity entity = gson.fromJson(response,ShopcarEntity.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                }else{
                    shopcarNum=entity.getList().get(0).getGoodsList().size();
                    land_cartnum.setText(shopcarNum+"");
                }
            }
        };
        OKUtilAPI.post(OKUtilAPI.shopList, "userId=" + userId+"&addrId="+AppConfig.CITY_ID, okUtilCallback);
    }

    private void initFirstData() {
        error_layout.setErrorType(EmptyLayout.NETWORK_LOADING);
        final String userId = SPUtils.getStringData(CommidContentActivity.this, SPUtils.USERID);
        final OkUtilCallback okUtilCallback = new OkUtilCallback(error_layout) {
            @Override
            public void onMyResponse(String response, int id) {
                DetailsBean detailsBean = gson.fromJson(response, DetailsBean.class);
                if(!detailsBean.getResult().equals("OK")){
                    BaseApplication.showToast(detailsBean.getResult());
                    error_layout.setErrorType(EmptyLayout.NODATA);
                }else if(detailsBean.getDetail()==null) {
                    error_layout.setErrorType(EmptyLayout.NODATA);
                }else{

                    if (AppConfig.RESULT_OK.equalsIgnoreCase(detailsBean.getResult())) {
                        goods = detailsBean.getDetail().getGoods();
                        goods.setNum(detailsBean.getDetail().getNum());
                        deBean=detailsBean.getDetail();
                        broList=detailsBean.getBrowseGoods();
                        likeList=detailsBean.getLikeBrandGoods();

                        isFollow=deBean.isIfFollow();
                        if (isFollow == false) {
                            initDetCollect();
                            initLandDetCollect();
                        }
                        if (isFollow == true) {
                            initCollect();
                            initLandCollect();
                        }
                        detailsData(goods);//商品详情数据适配
                        String goodsImgs = detailsBean.getGoodsImgs();//获取头部的图片路径
//                        Log.e("AGE", "temp----------" + goodsImgs);

                        temp = goodsImgs.split(",");
                        tems = goodsImgs.split(",");
                        if(tems.length>0){
                            AppConfig.IMAGE_URL = tems[0];
//                            Log.e("AGE", "temp----------" +temp[0] );
                        }
                        final List<String> imgl=new ArrayList<String>();
                        for(int p=0;p<temp.length;p++){
                            imgl.add(temp[p]);
                            arrayList.add(temp[p]);
                        }
                        String []nUrl=temp[0].split("\\.");
                        StringBuffer buffer=new StringBuffer();
                        buffer.append(nUrl[0]).append("_500.").append(nUrl[1]);
//                        if(nUrl[1].equals("jpg")){
//                            buffer.append(nUrl[0]).append("_500.jpg");
//                        }else if(nUrl[1].equals("png")){
//                            buffer.append(nUrl[0]).append("_500.png");
//                        }else if(nUrl[1].equals("jpeg")){
//                            buffer.append(nUrl[0]).append("_500.jpeg");
//                        }
//                        buffer.append(nUrl[0]).append("_500.jpg");
                        Glide.with(getApplicationContext()).load(OKUtilAPI.imgBaseUrl+buffer).into(land_goodimg);
                        landApater=new LandGoodImageAdapter(getApplicationContext(),imgl);
                        land_goodsmall.setAdapter(landApater);
                        land_goodsmall.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                for(int g=0;g<imgl.size();g++){
                                    LinearLayout landll= (LinearLayout) land_goodsmall.getChildAt(g).findViewById(R.id.land_bimg);
                                    landll.setBackgroundResource(R.drawable.land_banorimg);
                                }
                                LinearLayout landll= (LinearLayout) land_goodsmall.getChildAt(i).findViewById(R.id.land_bimg);
                                landll.setBackgroundResource(R.drawable.land_banimg);
                                String []aa=imgl.get(i).split("\\.");
                                StringBuffer b=new StringBuffer();
                                b.append(aa[0]).append("_500.").append(aa[1]);
//                                if(aa[1].equals("jpg")){
//                                    b.append(aa[0]).append("_500.jpg");
//                                }else if(aa[1].equals("png")){
//                                    b.append(aa[0]).append("_500.png");
//                                }else if(aa[1].equals("jpeg")){
//                                    b.append(aa[0]).append("_500.jpeg");
//                                }
//                                b.append(aa[0]).append("_500.jpg");
                                Glide.with(getApplicationContext()).load(OKUtilAPI.imgBaseUrl+b).into(land_goodimg);
                            }
                        });

                        num = goods.getNum();//商品数量
                        land_goodfashu.setText("发数: "+goods.getHair());
                        land_goodsort.setText("产品分类: "+deBean.getFirstSortName()+">"+deBean.getSortName());
                        land_goodnum.setText("商品货号: "+goods.getGoodsNum());
                        goodsId = detailsBean.getDetail().getGoods().getId();//商品id
                        xiaoliangg.setText("销量: "+goods.getSaleCount());
                        kucunc.setText("库存: "+goods.getNum());
                        land_goodallprice.setText("商品总价:￥ " + goods.getPrice());
                        String video=goods.getVedio();

                        AppConfig.GoodsId=goodsId+"";

                        if(!TextUtils.isEmpty(video)){
                            shiping.setVisibility(View.VISIBLE);
                        }else if(TextUtils.isEmpty(video)){
                            shiping.setVisibility(View.GONE);
                        }
                        String videoimg=goods.getVedioImg();
                        AppConfig.GOOD_VIDEO=video;
                        AppConfig.GOOD_VIDEOIMG=videoimg;
//                        if(!TextUtils.isEmpty(video)){
//                        }
//                        Log.e("AGE", "temp----------" + goodsId);
                        String addrId = goods.getAddrId();
                        AppConfig.AddrId_ID = addrId;//获取地址id
                        valuelist=detailsBean.getDetail().getParamsList();
                        if(valuelist.size()>0 && valuelist.size()<4){
                            goodApater=new GoodValueAdapter(mContext,valuelist);
                            yongList.setAdapter(goodApater);
                        }else if(valuelist.size()>3){
                            goodlimitApater=new GoodValueLimitAdapter(mContext,valuelist);
                            yongList.setAdapter(goodlimitApater);
                        }
                        initPager(tems.length);//头部的轮播
                        if(!TextUtils.isEmpty(userId)){
                            initBrohis();//浏览历史

                        }
                        if(likeList.size()>0){
                            initLikeGood();//相同{场景商品
                        }
                    }
                }
            }

        };
          if(goodsId1 == null && goodsNum != null)  {
              System.out.println("=============="+goodsNum+"=======================");
              String params="wid="+AppConfig.CITY_ID+"&userId="+userId+"&goodsNum="+goodsNum;
              OKUtilAPI.post(OKUtilAPI.CommidUrl, params, okUtilCallback);
          }else {
              System.out.println("======419========"+goodsId1+"=======================");
              String params = "wid=" + AppConfig.CITY_ID +"&id=" +goodsId1+ "&userId=" + userId;
              OKUtilAPI.post(OKUtilAPI.CommidUrl, params, okUtilCallback);
          }
    }
    private void initPager(final int a) {
        if(TDevice.isTablet(getApplicationContext())){
//            int width = (int)(TDevice.getScreenWidth()-80) /3;
//            RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(width,width);
//            bannerview.setLayoutParams(params2);
//            bannerview.getLayoutParams().width = width+360;
//            bannerview.getLayoutParams().height = width;
        }else{
            int width = (int)(TDevice.getScreenWidth()* 600 / 720);
//            int height = (int)(TDevice.getScreenWidth()-80)/2;
//            FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(width,height);
//            bannerview.setLayoutParams(params2);
//
            bannerview.getLayoutParams().width = width;
            bannerview.getLayoutParams().height = width;
        }
        ArrayList<Banner> banners = new ArrayList<>();
        for (int i = 0; i < a; i++) {
            Banner banner = new Banner();
            String []nUrl=tems[i].split("\\.");
            StringBuffer buffer=new StringBuffer();
            buffer.append(nUrl[0]).append("_500.").append(nUrl[1]);
//            if(nUrl[1].equals("jpg")){
//                buffer.append(nUrl[0]).append("_500.jpg");
//            }else if(nUrl[1].equals("png")){
//                buffer.append(nUrl[0]).append("_500.png");
//            }else if(nUrl[1].equals("jpeg")){
//                buffer.append(nUrl[0]).append("_500.jpeg");
//            }
//            buffer.append(nUrl[0]).append("_500.jpg");
            banner.setImgPath(OKUtilAPI.imgBaseUrl +  buffer);
            banner.setImgUrl(tems[i]);
            banners.add(banner);
        }
        bannerview.addView(BannerUtil.getloopviewpager(this, banners,"pic"));

    }
    private void initLikeGood() {
        final OkUtilCallback okUtilCallback = new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                DetailsBean detailsBean = gson.fromJson(response, DetailsBean.class);
                if(detailsBean.getResult().equals("OK")){
                    GoodLikeAdapter guessAdapter=new GoodLikeAdapter(CommidContentActivity.this, likeList);
                    land_goodleftview.setAdapter(guessAdapter);
                    land_goodleftview.setLayoutManager(new LinearLayoutManager(CommidContentActivity.this,LinearLayoutManager.VERTICAL,false));
                    guessAdapter.setOnItemClickListener(new GoodLikeAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View v, int i) {
                            Intent  intent = new Intent(CommidContentActivity.this, CommidContentActivity.class);
                            int id = likeList.get(i).getId();
                            intent.putExtra("id", String.valueOf(id));
                            startActivity(intent);
                        }

                        @Override
                        public void onItemLongClick(View v, int position) {

                        }
                    });
                }
            }
        };
        if(goodsId1 == null && goodsNum != null)  {
            System.out.println("=============="+goodsNum+"=======================");
            String params="wid="+AppConfig.CITY_ID+"&userId="+userId+"&goodsNum="+goodsNum;
            OKUtilAPI.post(OKUtilAPI.CommidUrl, params, okUtilCallback);
        }else {
            System.out.println("======494========"+goodsId1+"=======================");
            String params = "wid=" + AppConfig.CITY_ID +"&id=" +goodsId1+ "&userId=" + userId;
            OKUtilAPI.post(OKUtilAPI.CommidUrl, params, okUtilCallback);
        }
    }

    private void initBrohis() {
        GoodBrowAdapter guessAdapter=new GoodBrowAdapter(CommidContentActivity.this, broList);
        land_goodlbtview.setAdapter(guessAdapter);
        land_goodlbtview.setLayoutManager(new LinearLayoutManager(CommidContentActivity.this,LinearLayoutManager.VERTICAL,false));
        guessAdapter.setOnItemClickListener(new GoodBrowAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int i) {
                Intent  intent = new Intent(CommidContentActivity.this, CommidContentActivity.class);
                int id = broList.get(i).getId();
                intent.putExtra("id", String.valueOf(id));
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View v, int position) {

            }
        });
    }



    private void detailsData(DetailsBean.DetailBean.GoodsBean goods) {
        AppConfig.SP_NAME = goods.getName();
        AppConfig.SP_PRICE = goods.getPriceMk();
        AppConfig.SP_PRICE1 = goods.getPrice();
        land_goodname.setText(goods.getName());//商品信息名称
        commidinfo.setText(goods.getName());//商品信息名称
        land_goodprice.setText("￥" + NetUtils.setDecimal(goods.getPrice()));//商品折扣价
        commidprice.setText("￥" + NetUtils.setDecimal(goods.getPrice()));//商品折扣价
        land_goodpreprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//加横线
        zhepirce.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//加横线
        land_goodpreprice.setText("￥" + NetUtils.setDecimal(goods.getPriceMk()));//商品原价
        zhepirce.setText("￥" + NetUtils.setDecimal(goods.getPriceMk()));//商品原价
        land_goodsales.setText(goods.getSaleCount()+"件");
        land_goodkucun.setText("商品库存:"+goods.getNum());


    }
    @Override
    public void initData() {
        initFragment();//初始化fragment
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.tuwenButton:
                        showFragment(formatfileFragment);
                        break;
                    case R.id.xiaoguoButton:
                        showFragment(effectContextFragment);
                        break;
                    case R.id.yonghuButton:
                        showFragment(usersContextFragment);
                        break;
                }
            }
        });
    }

    private void initFragment() {
        formatfileFragment = new FormatFileFragment();
        effectContextFragment = new EffectContextFragment();
        usersContextFragment = new UsersContextFragment();

        fragmentManager = getSupportFragmentManager();
        currentFragment = formatfileFragment;
        showFragment(formatfileFragment);
    }

    private void showFragment(Fragment targetFragment) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//       if(!targetFragment.isVisible()){
//
//       }
        if (!targetFragment.isAdded()) {
            Bundle bundle=new Bundle();
            bundle.putString("goodsId", goodsId1);
            targetFragment.setArguments(bundle);
            fragmentTransaction.add(R.id.fragLayout, targetFragment).hide(currentFragment).show(targetFragment).commit();
        } else {
            fragmentTransaction.hide(currentFragment).show(targetFragment).commit();
        }
        currentFragment = targetFragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_commid_context;
    }

    @Override
    protected String getFragmentTag() {
        return null;
    }
  private Dialog customDialog;

    @OnClick({R.id.collectLayout, R.id.catLayout, R.id.cattext, R.id.buytext,R.id.shiping,R.id.land_cat,
      R.id.img_error_layout,R.id.land_add,R.id.land_score,R.id.land_reduce,R.id.land_buytext
    ,R.id.toplay,R.id.land_cole,R.id.land_buyll,R.id.land_kefull,R.id.land_tohome,R.id.land_goodimg})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.collectLayout://加入收藏
                if (SPUtils.getBooleanData(CommidContentActivity.this, SPUtils.ISLOGIN)) {
                    String userId = SPUtils.getStringData(CommidContentActivity.this, SPUtils.USERID);
                    //加入收藏的网址
                    shouUrl =  OKUtilAPI.SHOUC + "?userId=" + userId + "&id=" + goodsId + "&type=" + 0;
                    Log.i("yu","-"+shouUrl);
                    initNet(shouUrl);//加入收藏
                } else {
                    intent = new Intent(CommidContentActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.land_cole:
                if (SPUtils.getBooleanData(CommidContentActivity.this, SPUtils.ISLOGIN)) {
                    String userId = SPUtils.getStringData(CommidContentActivity.this, SPUtils.USERID);
                    //加入收藏的网址
                    String s = userId;
                    landshouUrl = OKUtilAPI.SHOUC + "?userId=" + userId +  "&id=" + goodsId+ "&type=" + 0;
//                    Log.i("yu","-"+shouUrl);
                    initNet(landshouUrl);//加入收藏
                } else {
                    intent = new Intent(CommidContentActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.catLayout://购物车
                intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("id", 1);
                AppConfig.TOMAIN="1";
                startActivity(intent);
                break;
            case R.id.land_buyll://购物车
                if(!SPUtils.getBooleanData(this,SPUtils.ISLOGIN)){
                    intent=new Intent(CommidContentActivity.this,LoginActivity.class);
                    startActivity(intent);
                }else {
                    intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.putExtra("id", 1);
                    AppConfig.TOMAIN="1";
                    startActivity(intent);
                }
                break;
            case R.id.cattext://加入购物车
                if(!SPUtils.getBooleanData(this,SPUtils.ISLOGIN)){
                    intent=new Intent(CommidContentActivity.this,LoginActivity.class);
                    startActivity(intent);
                }else {
                    if (NetUtils.isConnected(this)) {
                        initpopupWindow();//弹出对话框
                        AppConfig.TEMP=1;
                    }
                }
                break;
            case R.id.land_cat:
                //购物车网址
                if (SPUtils.getBooleanData(CommidContentActivity.this, SPUtils.ISLOGIN)) {
                    if(goods.getNum()>0 && AppConfig.TEMP <goods.getNum()){
                        catpath =  OKUtilAPI.CATURL + "?userId=" + userId + "&num=" + AppConfig.TEMP + "&goodsNum=" + goods.getGoodsNum() +"&addrId="+AppConfig.CITY_ID;
                        System.out.println("==============================="+catpath);
                        initLandNet(catpath);//加入购物车
                    }else{
                        ToastUtil.show(mContext,"很抱歉,该商品库存已不足,无法添加",1500);
                    }
                } else {
                    intent = new Intent(CommidContentActivity.this, LoginActivity.class);
                    startActivity(intent);
                }

                break;
            case R.id.buytext://立即购买
                if(!SPUtils.getBooleanData(this,SPUtils.ISLOGIN)){
                    intent=new Intent(CommidContentActivity.this,LoginActivity.class);
                    startActivity(intent);
                }else {
                    if (NetUtils.isConnected(this)) {
                        if(goods.getNum()>0 && AppConfig.TEMP <goods.getNum()){
                            AppConfig.TEMP = 1;//数量清零
                            initpopupWindow();//弹出对话框
                        }else{
                            ToastUtil.show(mContext,"很抱歉,该商品库存已不足,无法购买",1500);
                        }
                    }
                }
                break;
            case R.id.land_buytext:
                if (SPUtils.getBooleanData(CommidContentActivity.this, SPUtils.ISLOGIN)) {
                    if(goods.getNum()>0 && AppConfig.TEMP < goods.getNum()){
                        intent = new Intent(CommidContentActivity.this, AtOneBuyActivity.class);
                        intent.putExtra("goodprice",NetUtils.setDecimal(goods.getPrice())+"");
                        intent.putExtra("goodname",goods.getName());
                        intent.putExtra("goodid",goodsId+"");
                        startActivity(intent);
                    }else{
                        ToastUtil.show(mContext,"很抱歉,该商品库存已不足,无法购买",1500);
                    }
                } else {
                    intent = new Intent(CommidContentActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.add_cat://对话框中的加入购物车
                if (SPUtils.getBooleanData(CommidContentActivity.this, SPUtils.ISLOGIN)) {
                    num = AppConfig.TEMP;
                    if(goods.getNum()>0 &&  num <goods.getNum()){
                        //购物车网址
                        catpath =  OKUtilAPI.CATURL + "?userId=" + userId + "&num=" + num + "&goodsId=" + goodsId+"&addrId="+AppConfig.CITY_ID;
                        Log.e("TTTTT","catpath---------"+catpath);
                        initNet(catpath);//加入购物车
                    }else{
                        ToastUtil.show(mContext,"很抱歉,该商品库存已不足,无法添加",1500);
                    }
                } else {
                    intent = new Intent(CommidContentActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.go_buy://立即购买
                if (SPUtils.getBooleanData(CommidContentActivity.this, SPUtils.ISLOGIN)) {
                    if(goods.getNum()>0 && AppConfig.TEMP <goods.getNum()){
                        //                    Toast.makeText(CommidContentActivity.this, "跳转到立即购买页面", Toast.LENGTH_SHORT).show();
                        intent = new Intent(CommidContentActivity.this, AtOneBuyActivity.class);
                        intent.putExtra("goodprice",NetUtils.setDecimal(goods.getPrice())+"");
                        intent.putExtra("goodname",goods.getName());
                        intent.putExtra("goodid",goodsId+"");
                        startActivity(intent);
                        popupWindow.dismiss();
                        backgroundAlpha(this, 1f);
                    }else{
                        ToastUtil.show(mContext,"很抱歉,该商品库存已不足,无法购买",1500);
                    }
                } else {
                    intent = new Intent(CommidContentActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.cat_back://点击x键
                dialog.dismiss();
                break;
            case R.id.lookcat://查看购物车
                dialog.dismiss();
                intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("id", 1);
                AppConfig.TOMAIN="1";
                startActivity(intent);
                break;
            case R.id.stroll://再去逛逛
                dialog.dismiss();
//                intent = new Intent(getApplicationContext(), MainActivity.class);
//                intent.putExtra("id", 2);
//                startActivity(intent);
                break;
            case R.id.back_commid://点击x按钮
                popupWindow.dismiss();
                AppConfig.TEMP = 1;//数量清零
                backgroundAlpha(this, 1f);
                break;
            case R.id.land_add:
                if (AppConfig.TEMP >= 1) {
                    AppConfig.TEMP++;
                    land_score.setText(AppConfig.TEMP + "");
                    land_goodallprice.setText("商品总价:￥ " + goods.getPrice()*AppConfig.TEMP);
                }
                break;
            case R.id.land_reduce:
                if (AppConfig.TEMP == 1) {
                    land_score.setText(AppConfig.TEMP + "");
                } else {
                    AppConfig.TEMP--;
                    if (AppConfig.TEMP <= 10) {
                        land_goodallprice.setText("商品总价:￥ " + goods.getPrice()*AppConfig.TEMP);
                    }
                    land_score.setText(AppConfig.TEMP + "");
                }
                break;
            case R.id.land_score:
                break;
            case R.id.minus:
                if (AppConfig.TEMP == 1) {
                    score.setText(AppConfig.TEMP + "");
                } else {
                    AppConfig.TEMP--;
                    if (AppConfig.TEMP <= 10) {
                        diogpirce.setText("￥" + goods.getPriceMk());
                    }
                    score.setText(AppConfig.TEMP + "");
                }
                break;
            case R.id.add:
                if (AppConfig.TEMP >= 1) {
                    AppConfig.TEMP++;
                    score.setText(AppConfig.TEMP + "");
                    if (AppConfig.TEMP >= 10) {
                        diogpirce.setText("￥" + goods.getPrice());
                    }
                }
                break;
            case R.id.shiping:
                if(TextUtils.isEmpty(AppConfig.GOOD_VIDEO)){
                    ToastUtil.show(mContext,"很抱歉,该商品暂无视频",1500);
                }else{
                    intent=new Intent(getApplicationContext(),GoodVideoActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.img_error_layout:
                initFirstData();
                break;
            case R.id.toplay:
                if(TextUtils.isEmpty(AppConfig.GOOD_VIDEO)){
                    ToastUtil.show(getApplicationContext(),"很抱歉,该商品暂无视频",1500);
                }else{
                    intent=new Intent(getApplicationContext(),GoodVideoActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.land_kefull:
                customDialog=new Dialog(this);
                customDialog.setContentView(R.layout.contact_us_dialog);
                Window window=customDialog.getWindow();
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                RelativeLayout tocall_us= (RelativeLayout) customDialog.findViewById(R.id.tocall_us);
                TextView phone= (TextView) customDialog.findViewById(R.id.custom_tell);
                phone.setText("客服热线:"+myPhone);
                customDialog.setCanceledOnTouchOutside(true);
                tocall_us.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent  gg = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + myPhone));//跳转到拨号界面，同时传递电话号码
                        startActivity(gg);
                        customDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp=customDialog.getWindow().getAttributes();
                lp.gravity= Gravity.RIGHT;
                customDialog.getWindow().setAttributes(lp);

                try{
                    Context context = customDialog.getContext();
                    int divierId = context.getResources().getIdentifier("android:id/titleDivider", null, null);
                    View divider = customDialog.findViewById(divierId);
                    divider.setBackgroundColor(Color.TRANSPARENT);
                }catch(Exception e){
                    //去除Holo主题的蓝色线条
                    e.printStackTrace();
                }
                customDialog.show();
                break;
            case R.id.land_tohome:
//                ((MainActivity)getApplicationContext()).showHomePageFragment();
                intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("id", 2);
                AppConfig.TOMAIN="2";
                startActivity(intent);
                break;
            case R.id.land_goodimg:
                ShareImgActivity.startIntent(mContext,arrayList,0);
                break;
        }
    }

    private void initLandNet(String catpath) {
        JsonHttpNet.dataDownNet(catpath, new JsonHttpNet.HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                Entity entity = gson.fromJson(response, Entity.class);
                if (AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult())) {
                    //弹出对话框

                    AddCatDiolgg();
                    getShopNum();
                } else {
                    Toast.makeText(CommidContentActivity.this, entity.getResult(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Exception e) {

            }
        });
    }

    private void AddCatDiolgg() {
        land_score.setText("" + 1);//数量清零
//        score.setText("" + 1);//数量清零
//        popupWindow.dismiss();
//        backgroundAlpha(CommidContentActivity.this, 1f);
        dialog = new Dialog(CommidContentActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉dialog的头部
        dialog.setContentView(R.layout.cat_us_dialog);
        TextView lookcat = (TextView) dialog.findViewById(R.id.lookcat);
        TextView stroll = (TextView) dialog.findViewById(R.id.stroll);
        ImageView backImage = (ImageView) dialog.findViewById(R.id.cat_back);
        backImage.setOnClickListener(CommidContentActivity.this);
        lookcat.setOnClickListener(CommidContentActivity.this);//查看购物车
        stroll.setOnClickListener(CommidContentActivity.this);//回去逛逛
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        AppConfig.isRefreshShocpar = true;
    }

    private void initNet(String url) {
        Log.i("url1111111111",url);
        if (NetUtils.isConnected(this)) {
            if (url.equals(catpath)) {
                JsonHttpNet.dataDownNet(catpath, new JsonHttpNet.HttpCallbackListener() {
                    @Override
                    public void onFinish(String response) {
                        Entity entity = gson.fromJson(response, Entity.class);
                        if (AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult())) {
                            //弹出对话框

                            AddCatDiolg();
                            land_cartnum.setText(AppConfig.CARTTEMP+1+ "");
                        } else {
                            Toast.makeText(CommidContentActivity.this, entity.getResult(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
            }
            if (url.equals(shouUrl)) {
                JsonHttpNet.dataDownNet(shouUrl, new JsonHttpNet.HttpCallbackListener() {
                    @Override
                    public void onFinish(String response) {
                        goodsCollectBean = gson.fromJson(response, GoodsCollectBean.class);//收藏的bean
                        if (AppConfig.RESULT_OK.equalsIgnoreCase(goodsCollectBean.getResult())) {
                            flag = goodsCollectBean.getFlag();
                            if (flag == 1) {//加入收藏
                                initCollect();
                            } else if (flag == 0) {//取消收藏
                                initDetCollect();
                            }
                        } else {
                            Toast.makeText(CommidContentActivity.this, goodsCollectBean.getResult(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
            }
            if (url.equals(landshouUrl)) {
                JsonHttpNet.dataDownNet(landshouUrl, new JsonHttpNet.HttpCallbackListener() {
                    @Override
                    public void onFinish(String response) {
                        goodsCollectBean = gson.fromJson(response, GoodsCollectBean.class);//收藏的bean
                        if (AppConfig.RESULT_OK.equalsIgnoreCase(goodsCollectBean.getResult())) {
                            flag = goodsCollectBean.getFlag();
                            if (flag == 1) {//加入收藏
                                initLandCollect();
                            } else if (flag == 0) {//取消收藏
                                initLandDetCollect();
                            }
                        } else {
                            Toast.makeText(CommidContentActivity.this, goodsCollectBean.getResult(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
            }
        } else {
            Toast.makeText(CommidContentActivity.this, "请检查你的网络", Toast.LENGTH_SHORT).show();
        }
    }

    private void initDetCollect() {
        startImage.setImageResource(R.mipmap.shouuu);
        land_collectiontv.setText("收藏");
    }
    private void initCollect() {
        startImage.setImageResource(R.mipmap.sssssss);
        land_collectiontv.setText("已收藏");
    }
    private void initLandDetCollect() {
        land_collectionimg.setImageResource(R.mipmap.landshoucang);
        land_collectiontv.setText("收藏");
    }
    private void initLandCollect() {
        land_collectionimg.setImageResource(R.mipmap.shouuu);
        land_collectiontv.setText("已收藏");
    }
    private void AddCatDiolg() {
        land_score.setText("" + 1);//数量清零
        score.setText("" + 1);//数量清零
        popupWindow.dismiss();
        backgroundAlpha(CommidContentActivity.this, 1f);
        dialog = new Dialog(CommidContentActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉dialog的头部
        dialog.setContentView(R.layout.cat_us_dialog);
        TextView lookcat = (TextView) dialog.findViewById(R.id.lookcat);
        TextView stroll = (TextView) dialog.findViewById(R.id.stroll);
        ImageView backImage = (ImageView) dialog.findViewById(R.id.cat_back);
        backImage.setOnClickListener(CommidContentActivity.this);
        lookcat.setOnClickListener(CommidContentActivity.this);//查看购物车
        stroll.setOnClickListener(CommidContentActivity.this);//回去逛逛
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        AppConfig.isRefreshShocpar = true;
    }

    private void initpopupWindow() {
        popupContentView = LayoutInflater.from(CommidContentActivity.this).inflate(R.layout.cat_commid_activity, null);
        popupWindow = new PopupWindow(popupContentView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
        popupWindow.showAtLocation(popupContentView, Gravity.BOTTOM, 0, 0);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.color.main_gray));

        // 设置好参数之后再show
        //设置窗体背景颜色
        backgroundAlpha(this, 0.5f);
//        popupWindow.setOutsideTouchable(true);
//        popupWindow.setFocusable(true);
//        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//
//        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                popupWindow.dismiss();
//            }
//        });
//
//
//        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                if(motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE){
//                   popupWindow.dismiss();
//                    return true;
//                }
//                return false;
//            }
//        });

        TextView bianhao = (TextView) popupContentView.findViewById(R.id.bianhao);//编号
        TextView kutext = (TextView) popupContentView.findViewById(R.id.text_ku);//库存
        TextView yishou = (TextView) popupContentView.findViewById(R.id.text_yishou);//已售
        ImageView topImage = (ImageView) popupContentView.findViewById(R.id.topImage);//商品照片
        diogpirce = (TextView) popupContentView.findViewById(R.id.diogpirce);//价格
        score = (TextView) popupContentView.findViewById(R.id.score);//数量
        backCommid = (ImageView) popupContentView.findViewById(R.id.back_commid);//x按钮
        goBuy = (TextView) popupContentView.findViewById(R.id.go_buy);//立即购买
        addCar = (TextView) popupContentView.findViewById(R.id.add_cat);//加入购物车
        minus = (TextView) popupContentView.findViewById(R.id.minus);//减号
        add = (TextView) popupContentView.findViewById(R.id.add);//加号

        backCommid.setOnClickListener(this);
        addCar.setOnClickListener(this);
        goBuy.setOnClickListener(this);
        add.setOnClickListener(this);
        minus.setOnClickListener(this);
        initDiolg(kutext, yishou, topImage);//对话框里的的数据适配
    }


    private void initDiolg(TextView kutext, TextView yishou, ImageView topImage) {
        //对话框中适配数据

        if(TDevice.isTablet(getApplicationContext())){
            int width = (int)(TDevice.getScreenWidth()-40)/7;
            int height = (int)(TDevice.getScreenWidth()-40)/9;
            FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(width,height);
            topImage.setLayoutParams(params2);
        }else{
            int width = (int)(TDevice.getScreenWidth()-40)/4;
//            int height = (int)(TDevice.getScreenWidth()-40)/9;
            FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(width,width);
            topImage.setLayoutParams(params2);
        }

        String []nUrl=AppConfig.IMAGE_URL.split("\\.");
        StringBuffer buffer=new StringBuffer();
        buffer.append(nUrl[0]).append("_360.").append(nUrl[1]);
//        if(nUrl[1].equals("jpg")){
//            buffer.append(nUrl[0]).append("_360.jpg");
//        }else if(nUrl[1].equals("png")){
//            buffer.append(nUrl[0]).append("_360.png");
//        }else if(nUrl[1].equals("jpeg")){
//            buffer.append(nUrl[0]).append("_360.jpeg");
//        }
//        buffer.append(nUrl[0]).append("_360.jpg");
        Glide.with(this).load(OKUtilAPI.imgBaseUrl +buffer).into(topImage);
        diogpirce.setText("￥" + goods.getPrice());
        yishou.setText("已售：" + goods.getSaleCount());
        kutext.setText("库存：" + goods.getNum());
    }

    private void backgroundAlpha(CommidContentActivity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppConfig.TEMP = 1;
    }
}
